<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/4/21 10:33
 * Desc:
 */

namespace App\Service;

use App\Lib\Common;
use App\Models\Admin\Menu;
use App\Models\Admin\Menu as MenuModel;


class MenuService extends BaseService
{
    //获取菜单列表
    public function list($params = []) {
        $data = (new MenuModel())->getList($params)->toArray();
        if (empty($data)) {
            return ["error" => 70000, "msg" => "没有添加菜单"];
        }
        //整理数据
        $dataTree = [];
        for ($i = 0; $i < count($data); $i++) {
            $dataTree[] = ["id" => $data[$i]['id'],
                "parent_id" => $data[$i]['parent_id'],
                "name" => $data[$i]['name'],
                "uri" => $data[$i]['uri'],
                "sort"=>$data[$i]['sort'],
                "created_at" => date('Y-m-d H:i:s', strtotime($data[$i]['created_at']))];
        }
        return $dataTree;
    }

    //获取下拉菜单列表树
    public function tree() {
        $menus = (new Menu())->getList([])->toArray();
        $menus = Common::getTree($this->params($menus));
        $add = ["id" => 0, "parent_id" => 0, "name" => "顶部菜单"];
        array_unshift($menus, $add);
        return $menus;
    }

    //处理参数信息
    public function params($data) {
        foreach ($data as $k => $d) {
            if (!empty($d["data"])) {
                $data[$k]["data"] = json_decode($d["data"], true);
            }
        }
        return $data;
    }

    //获取单个菜单
    public function getOne($id) {
        $one = (new MenuModel())->getOne($id);
        //处理路由参数
        if(!empty($one["data"])||null!=$one["data"]||""!=$one["data"]){
            $data = json_decode($one["data"],true);
            $str="";
            foreach ($data as $k=>$d){
                $str.=$k."|".$d."\r\n";
            }
            $one["data"]=$str;
        }
        return $one;
    }

    /**
     * 排序
     */
    public function setSort($id,$sort){
        return (new MenuModel())->where("id",$id)->update(["sort"=>$sort]);
    }
}
